import {
  currMap$,
  allMaps,
  currNpc$,
  currNpcOptions$,
  destNpc$,
  destNpcOptions$,
  destMap$,
  pics
} from 'data'
import type { Entity } from 'data'
import {
  action,
  observable,
  makeAutoObservable,
  runInAction,
  autorun
} from 'mobx'
export type EntityOption = Entity & { value: string; label: string }
const entityToEntityOption: (i: Entity) => EntityOption = (i: Entity) => ({
  ...i,
  value: i.text,
  label: i.text
})
export class NpcStore {
  constructor() {
    makeAutoObservable(this)
  }
  allMapOption = allMaps.map(entityToEntityOption)
  @observable currMap = ''
  @observable currNpcOptions: EntityOption[] = []
  @observable currNpc = ''
  @observable destNpcOptions: EntityOption[] = []
  @observable destNpc = ''
  @observable destMap = ''
  @observable currMapPicture = ''
  @observable destMapPicture = ''

  setCurrMap(value: string) {
    currMap$.next(value)
  }
  setCurrNpc(value: string) {
    currNpc$.next(value)
  }
  setDestNpc(value: string) {
    destNpc$.next(value)
  }
  @action
  init() {
    currMap$.subscribe((data) => {
      let picture = ''
      if (data in pics) {
        picture = pics[data]
      }
      runInAction(() => {
        this.currMap = data
        this.currMapPicture = picture
      })
    })
    currNpc$.subscribe((data) => {
      runInAction(() => {
        this.currNpc = data
      })
    })
    currNpcOptions$.subscribe((data) => {
      runInAction(() => {
        this.currNpcOptions = data.map(entityToEntityOption)
      })
    })
    destNpcOptions$.subscribe((data) => {
      runInAction(() => {
        this.destNpcOptions = data.map(entityToEntityOption)
      })
    })
    destNpc$.subscribe((data) => {
      runInAction(() => {
        this.destNpc = data
      })
    })
    destMap$.subscribe((data) => {
      let picture = ''
      if (data in pics) {
        picture = pics[data]
      }
      runInAction(() => {
        this.destMap = data
        this.destMapPicture = picture
      })
    })
  }
}

export const npcStore = new NpcStore()
npcStore.init()
